<!--
 * @Author: 赵克强 huohuo625@163.com
 * @Date: 2023-11-06 15:18:43
 * @LastEditors: 赵克强 huohuo625@163.com
 * @LastEditTime: 2025-04-14 17:45:55
 * @FilePath: \hy-ui\src\views\render\pager\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!--
 * @Author: 赵克强 huohuo625@163.com
 * @Date: 2023-11-06 15:19:02
 * @LastEditors: 赵克强 huohuo625@163.com
 * @LastEditTime: 2024-07-23 17:51:45
 * @FilePath: \hy-ui\src\views\render\form\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE,
-->
<template>
  <div class="pager" style="margin: 12px" v-loading="loading">
    <div class="pageMain">
      <el-card class="box-card" style="padding: 0px; margin-right: 8px" v-if="['leftTreeRightTableDept', 'leftTreeRightTable'].includes(
        searchJson && searchJson.pageType
      )
        ">
        <div class="tree">
          <div class="treeList">
            <leftTree :getList="getCrudQueryList" ref="leftTree" :searchJson="searchJson" />
          </div>
        </div>
      </el-card>
      <el-card class="box-card mainRenderCard" style="padding: 8px; width: 100%">
        <div class="right" :style="{
          width: ['leftTreeRightTableDept', 'leftTreeRightTable'].includes(
            searchJson && searchJson.pageType
          )
            ? '100%'
            : '100%',
        }">
          <pagerSearchCondition ref="pagerSearchCondition" :searchJson="searchJson" :getList="getCrudQueryList" :init="init" :pageCode="pageCode"
            :openModal="openModal" :dictData="dictData" :resetData="resetData" :interfaceList="interfaceList" :total="total"
            v-if="searchJson && isRenderSearch" />
          <pagerTable ref="pagerTable" :tableColumns="tableColumns" :searchJson="searchJson" :getList="getCrudQueryList"
            :tableData="tableData" :openModal="openModal" :dictData="dictData" :openZbModal="openZbModal"
            :interfaceList="interfaceList" :isLeft="['tree'].includes(searchJson && searchJson.pageType)"
            v-if="searchJson && tableColumns && isRenderTable" />
        </div>
      </el-card>
    </div>
    <operateModal v-if="open" :open="open" :close="close" :title="title" :tableColumns="tableColumns"
      :modelLoading="modelLoading" :getList="zbOpen ? $refs.zbRef.getCrudQueryList : getCrudQueryList"
      :modalConfig="modalConfig" />
    <zbModel v-if="zbOpen" :open="zbOpen" ref="zbRef" :close="() => (zbOpen = false)" :title="title" :zbProps="{
      searchJsonZb,
      dictDataZb,
      tableColumnsZb,
      openModal,
      zbItemConfig,
      zbRowData,
    }" />
  </div>
</template>

<script>
import {
  getConfig,
  crudQuery,
  crudQueryList,
  getFormConfig,
  appDictData,
  frontViewData,
  batchListByType,
  getFormConfigFlow,
  getSystemDictLists,
} from "@/api/render/pager.js";
import pagerSearchCondition from "@/views/render/components/pagerSearchCondition";
import pagerTable from "@/views/render/components/pagerTable.vue";
import operateModal from "@/views/render/components/operateModal.vue";
import zbModel from "@/views/render/components/zbModel.vue";
import request from "@/utils/request";
import leftTree from "@/views/render/components/leftTree.vue";
import { list } from "@/api/system/customInterface";
export default {
  name: "pager",
  components: {
    pagerSearchCondition,
    pagerTable,
    operateModal,
    zbModel,
    leftTree,
  },
  data() {
    return {
      searchJson: null,
      tableColumns: null,
      loading: false,
      pageCode: undefined,
      tableList: {},
      open: false,
      title: "",
      modelLoading: false,
      modalConfig: null,
      dictList: [],
      systemDictList: [],
      dictData: {},
      tableData: {},
      zbOpen: false,
      searchJsonZb: null,
      dictListZb: [],
      dictDataZb: {},
      tableColumnsZb: null,
      zbItemConfig: null,
      zbRowData: null,
      interfaceList: {},
      isRenderSearch: false,
      isRenderTable: false,
      total:0
    };
  },
  props: ["name"],
  async mounted() {
    await this.init()
  },

  methods: {
    async init() {
      if (
        this.$route.path.includes(this.firstLetterToLowerCase(this.$route.name))
      ) {
        this.loading = true;
        await this.getConfigJson(this.firstLetterToLowerCase(this.$route.name));
        await this.getCrudQuery(this.firstLetterToLowerCase(this.$route.name));
        this.pageCode = this.firstLetterToLowerCase(this.$route.name);
        await this.getCrudQueryList();
        this.loading = false;
      } else if (this.$route.path.includes(this.$route.name)) {
        this.loading = true;
        await this.getConfigJson(this.firstLetterToLowerCase(this.$route.name));
        await this.getCrudQuery(this.$route.name);
        await this.getCrudQueryList();
        this.pageCode = this.$route.name;
        this.loading = false;
      } else {
        return this.$message.error("未知错误,请联系管理员");
      }
    },
    async openZbModal(item, row) {
      this.zbItemConfig = item;
      this.zbRowData = row;
      this.loading = true;
      this.title = item.label;
      // 查询条件
      const res = await getConfig(item.zbCode);
      this.searchJsonZb = res.body || {};
      const dictList = [];
      this.searchJsonZb?.filter?.body?.columns?.forEach((item) => {
        if (item["type"] === "dic") {
          dictList.push(item.formatQ);
        }
      });
      this.dictListZb = Array.from(new Set(dictList));
      // 表格配置
      const resTable = await crudQuery({ pageCode: item.zbCode });
      const dictListTable = [];
      if (resTable.code === 200) {
        this.tableColumnsZb = resTable.data || {};
        this.tableColumnsZb?.columns?.forEach((item) => {
          if (item["type"] === "dic") {
            dictListTable.push(item.format);
          }
        });
        this.dictListZb = Array.from(
          new Set([...this.dictListZb, ...dictListTable])
        );
        if (this.dictListZb?.length && this.dictListZb.toString()) {
          const resDict = await batchListByType(this.dictListZb.toString());
          if (resDict.code === 200) {
            this.dictDataZb = resDict.data || [];
          }
        }
      }
      this.loading = false;
      this.zbOpen = true;
    },
    async openModal(item, row) {
      this.title = item.label;
      let res = undefined;
      // 这一步获取表单JSON渲染表单

      res = await getFormConfig(row ? item.formId : item.tooltip);
      if (res.code === 200 && res.data?.formConfig && res.data?.widgetList) {
        let modalConfig = {};
        modalConfig = {
          ...res.data,
          formConfig: JSON.parse(res.data.formConfig),
          widgetList: JSON.parse(res.data.widgetList),
          itemConfig: item,
        };

        if (
          item.buttonType === "handleAdd" &&
          !!modalConfig.formConfig.addInitInterface
        ) {
          const viewData = await request({
            url: modalConfig.formConfig.addInitInterface,
            method: "get",
          });
          modalConfig.detailData = { ...viewData.data };
        }
        // 这一步获取回显数据
        if (row) {
          const detailRes = await frontViewData(item.tooltip, { id: row.id });
          if (detailRes.code === 200) {
            modalConfig.detailData = { ...detailRes.data };
          }
        }
        this.open = true;
        this.modelLoading = true;
        this.modalConfig = modalConfig;
      }
      this.modelLoading = false;
    },
    close() {
      this.open = false;
    },
    firstLetterToLowerCase(str) {
      return str.charAt(0).toLowerCase() + str.slice(1);
    },
    async getConfigJson(code) {
      this.loading = true;
      this.isRenderSearch = false;
      const res = await getConfig(code);
      this.searchJson = res.body || {};
      const dictList = [];
      const systemDictList = [];
      for (let i = 0; i < this.searchJson?.filter?.body?.columns?.length; i++) {
        const item = this.searchJson?.filter?.body?.columns?.[i];
        if (item["type"] === "dic" && item.formatTypeQ === "2") {
          systemDictList.push(item.formatQ);
        }
        if (
          item["type"] === "dic" &&
          (item.formatTypeQ === "1" || !item.formatTypeQ)
        ) {
          dictList.push(item.formatQ);
        }
        if (item["type"] === "custom") {
          item.formatQ = item.formatQ && JSON?.parse(item.formatQ);
          if (item.formatQ.url) {
            const updateRes = await list({ pageNum: 1, pageSize: 999 });
            if (updateRes.code === 200) {
              const updateFormat = updateRes.rows.filter(
                (b) => b.id === item.formatQ?.id
              );
              if (updateFormat.length) {
                item.formatQ = updateFormat[0];
              }
            }
          }
          const dataRouteArr =
            item.formatQ.app === "1"
              ? ["data", "rows"]
              : item.formatQ.returnDataPath.split(".");
          const requestConfig = {
            url:
              item.formatQ.app === "1"
                ? `/frontView/page/crudQuery/${item.formatQ.url}`
                : item.formatQ.url,
            method:
              item.formatQ.app === "1" ? "post" : item.formatQ.requestMethod,
          };
          const apiParams = {};
          if (item.formatQ.requestParam) {
            const data = JSON.parse(item.formatQ.requestParam);
            if (data.length) {
              data.forEach((item) => {
                apiParams[item.label] = item.value;
              });
              if (item.formatQ.requestMethod === "get") {
                requestConfig.params = apiParams;
              } else {
                requestConfig.data = apiParams;
              }
            }
          }
          const interData = await request(requestConfig);
          if (interData.code === 200) {
            let interList = interData;
            dataRouteArr.forEach((x) => {
              interList = interList[x];
            });

            this.interfaceList[item.name] = interList;
          }
        }
      }
      this.dictList = Array.from(new Set(dictList));
      this.systemDictList = Array.from(new Set(systemDictList));
      // if (this.dictList?.length && this.dictList.toString()) {
      //   const res = await batchListByType(this.dictList.toString());
      //   if (res.code === 200) {
      //     this.dictData = res.data || [];
      //   }
      // }
      this.loading = false;
      this.isRenderSearch = true;
    },
    async getCrudQuery(code) {
      this.loading = true;
      this.isRenderTable = false;
      const res = await crudQuery({ pageCode: code });
      const dictList = [];
      const systemDictList = [];
      if (res.code === 200) {
        this.tableColumns = res.data || {};
        for (let i = 0; i < this.tableColumns?.columns?.length; i++) {
          const item = this.tableColumns?.columns[i];
          if (item["type"] === "dic" && item.formatType === "2") {
            systemDictList.push(item.formatQ);
          }
          if (
            item["type"] === "dic" &&
            (item.formatType === "1" || !item.formatType)
          ) {
            dictList.push(item.format);
          }
          if (item["type"] === "custom") {
            item.format = item.format && JSON?.parse(item.format);
            if (item.format.url) {
              const updateRes = await list({ pageNum: 1, pageSize: 999 });
              if (updateRes.code === 200) {
                const updateFormat = updateRes.rows.filter(
                  (b) => b.id === item.format?.id
                );
                if (updateFormat.length) {
                  item.format = updateFormat[0];
                }
              }
            }
            const dataRouteArr =
              item.format.app === "1"
                ? ["data", "rows"]
                : item.format.returnDataPath.split(".");
            const requestConfig = {
              url:
                item.format.app === "1"
                  ? `/frontView/page/crudQuery/${item.format.url}`
                  : item.format.url,
              method:
                item.format.app === "1" ? "post" : item.format.requestMethod,
            };
            const apiParams = {};
            if (item.format.requestParam) {
              const data = JSON.parse(item.format.requestParam);
              if (data.length) {
                data.forEach((item) => {
                  apiParams[item.label] = item.value;
                });
                if (item.format.requestMethod === "get") {
                  requestConfig.params = apiParams;
                } else {
                  requestConfig.data = apiParams;
                }
              }
            }
            const interData = await request(requestConfig);
            if (interData.code === 200) {
              let interList = interData;
              dataRouteArr.forEach((x) => {
                interList = interList[x];
              });

              this.interfaceList[item.name] = interList;
            }
          }
        }
        this.dictList = Array.from(new Set([...this.dictList, ...dictList]));
        this.systemDictList = Array.from(
          new Set([...this.systemDictList, ...systemDictList])
        );
        if (this.dictList?.length && this.dictList.toString()) {
          const res = await batchListByType(this.dictList.toString());
          if (res.code === 200) {
            this.dictData = { ...this.dictData, ...res.data };
          }
        }
        if (this.systemDictList?.length && this.systemDictList.toString()) {
          const res = await getSystemDictLists(this.systemDictList.toString());
          if (res.code === 200) {
            this.dictData = { ...this.dictData, ...res.data };
          }
        }
      }
      this.loading = false;
      this.isRenderTable = true;
    },
    resetData() {
      this.$refs.leftTree?.resetData();
      this.$refs.pagerTable?.resetData();
    },
    async getCrudQueryList() {
      this.loading = true;
      const params = {
        ...this.$refs.pagerSearchCondition?.form,
        ...this.$refs.pagerTable?.queryParams,
        ...this.$refs.leftTree?.clickValue,
      };
      try {
        const res = await crudQueryList(this.pageCode, params);
        if (res.code === 200) {
          this.tableData = res.data;
          this.$refs.pagerTable?.totalNum(res.data.count);
          this.total = res.data.count
          this.loading = false;
        }
      } catch (error) {
        this.loading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.pager {

}

.pageMain {
  display: flex;
  flex-direction: row;
  width: 100%;
  ::v-deep .mainRenderCard {
    overflow: auto;
    min-height: 88vh !important;
  }
  .right {
    width: 100%;
  }
}

.treeList {
  height: 80vh;
}

.tree {
  margin-right: 24px;
  float: left;
}
</style>